<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import DatavVew from '@/components/DatavVew.vue'
import axios from 'axios'
import qs from 'qs'

/* -------------------- 状态 -------------------- */
const modalVisible = ref(false)
const datavVew     = ref(null)

const tableData = ref([])
const fileType  = ref('shp')          // 单选框值：shp / geojson
const fileList  = ref([])

/* -------------------- 列定义 -------------------- */
const columns = [
  { title: '表名', dataIndex: 'name', key: 'name' },
  {
    title : '操作',
    dataIndex: 'action',
    key   : 'action',
    slots : { customRender: 'bodyCell' }   // 让 #bodyCell 生效
  }
]

/* -------------------- 业务方法 -------------------- */
const showModal = (name) => {
  modalVisible.value = true
  axios.get('/server-api/gis/getFeatureCollection', {
    params           : { tableName: name },
    paramsSerializer : (p) => qs.stringify(p),
  })
  .then(res => datavVew.value?.setData(res.data))
  .catch(() => message.error('获取数据失败'))
}

/* 下载功能：根据当前 fileType 调用后台下载接口 */
const downloadFile = (name) => {
  axios.get('/server-api/gis/download', {
    params: { tableName: name, fileType: fileType.value },
    responseType: 'blob'                      // 后端返回文件流
  })
  .then(res => {
    // 生成临时链接并触发下载
    const blob = new Blob([res.data])
    const url  = window.URL.createObjectURL(blob)
    const a    = document.createElement('a')
    a.href     = url
    a.download = `${name}.${fileType.value === 'shp' ? 'zip' : 'geojson'}`
    a.click()
    window.URL.revokeObjectURL(url)
  })
  .catch(() => message.error('下载失败'))
}

/* -------------------- 上传相关（保持不变） -------------------- */
const getExt      = (f) => f.slice(f.lastIndexOf('.')).toLowerCase()
const getBaseName = (f) => f.slice(0, f.lastIndexOf('.')).toLowerCase()

const beforeUpload = (file) => {
  const ext = getExt(file.name)
  if (fileType.value === 'geojson') {
    if (!(ext === '.json' || ext === '.geojson')) {
      message.warning('只能上传 .json 或 .geojson 文件')
      return false
    }
    if (!fileList.value.find(f => f.name === file.name)) fileList.value.push(file)
    return false
  }
  const validExts = ['.shp', '.shx', '.dbf', '.prj', '.cpg']
  if (!validExts.includes(ext)) {
    message.error('SHP 相关文件必须是 .shp/.shx/.dbf/.prj/.cpg')
    return false
  }
  if (!fileList.value.find(f => f.name === file.name)) fileList.value.push(file)
  return false
}

const uploadFiles = () => {
  if (fileType.value === 'geojson') {
    message.error('GeoJSON上传尚未实现'); return
  }
  const required = ['.shp', '.shx', '.dbf']
  const exts     = fileList.value.map(f => getExt(f.name))
  const miss     = required.filter(e => !exts.includes(e))
  if (miss.length) {
    message.error(`缺少文件：${miss.join('、')}`); return
  }
  const fd = new FormData()
  fileList.value.forEach(f => fd.append('files', f))
  axios.post('/server-api/gis/shapefile', fd,
    { headers: { 'Content-Type': 'multipart/form-data' } })
    .then(() => { message.success('上传成功'); fileList.value = [] })
    .catch(() => message.error('上传失败'))
}

/* -------------------- 初始化 -------------------- */
onMounted(() => {
  axios.get('/server-api/gis/getGeomTables')
    .then(res => { tableData.value = res.data.map(name => ({ name })) })
    .catch(()  => console.error('接口调用失败'))
})
</script>

<template>
  <div class="main">
    <!-- 顶部操作区 -->
    <a-space style="margin-bottom:16px;">
      <a-radio-group v-model:value="fileType" size="middle">
        <a-radio-button value="shp">SHP文件</a-radio-button>
        <a-radio-button value="geojson">GeoJSON文件</a-radio-button>
      </a-radio-group>

      <a-upload
        :multiple="true"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :show-upload-list="true"
        :custom-request="{ doNothing: true }">
        <a-button>选择文件</a-button>
      </a-upload>

      <a-button type="primary"
                :disabled="fileList.length === 0"
                @click="uploadFiles">
        手动上传
      </a-button>
    </a-space>

    <!-- 表格 -->
    <a-table :columns="columns" :data-source="tableData" row-key="name">
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'action'">
          <a-button type="link" @click="showModal(record.name)">浏览</a-button>
          <a-divider type="vertical" />
          <a-button type="link" @click="downloadFile(record.name)">下载</a-button>
        </template>
        <template v-else>
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </a-table>

    <!-- 全屏弹窗 -->
    <a-modal v-model:visible="modalVisible"
             width="100vw"
             :body-style="{ height:'100vh',padding:0 }"
             :footer="null"
             closable centered destroyOnClose>
      <div style="width:100%;height:100%;display:flex;justify-content:center;align-items:center;">
        <DatavVew ref="datavVew" />
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.main { width:100%; height:100%; padding:12px; background:#f5f7fa; }

/* 你原来的深度样式保持 */
::v-deep(.ant-radio-group){border:1px solid #d9d9d9;border-radius:6px;background:#fff;padding:2px;}
::v-deep(.ant-radio-button-wrapper){min-width:80px;text-align:center;font-weight:600;}
::v-deep(.ant-radio-button-wrapper-checked){background:#1890ff;color:#fff;border-color:#1890ff;}
</style>
